#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::weak_ptr;
using std::shared_ptr;

void test()
{
    /* weak_ptr<int> wp(new int(20));//error */
    weak_ptr<int> wp;//空对象

    {
        shared_ptr<int> sp(new int(10));
        cout << "*sp = " << *sp << endl;
        cout << "sp.use_count() = " << sp.use_count() << endl;

        cout << endl;
        wp = sp;//将sp赋值给wp
        //如何查看weak_ptr关联的资源是否还存在
        //1、使用引用计数进行查看
        cout << "sp.use_count() = " << sp.use_count() << endl;
        cout << "wp.use_count() = " << wp.use_count() << endl;

        cout << endl;
        //2、expired函数查看关联的空间是否存在
        bool flag = wp.expired();
        if(flag)
        {
            cout << "关联的资源已经销毁了" << endl;
        }
        else
        {
            cout << "关联的资源依旧存在" << endl;
        }

        cout << endl;
        //3、lock函数，将weak_ptr提升为shared_ptr
        shared_ptr<int> sp2 = wp.lock();
        if(sp2)
        {
            cout << "提升成功,关联的资源还在";
            cout << "*sp2 = " << *sp2 << endl;
            cout << "sp.use_count() = " << sp.use_count() << endl;
            cout << "sp2.use_count() = " << sp2.use_count() << endl;
            cout << "wp.use_count() = " << wp.use_count() << endl;
        }
        else
        {
            cout << "提升失败，关联的资源已经销毁了" << endl;
        }
    }

    cout << endl << "离开作用域的时候" << endl;
    //sp与sp2还存在吗
    cout << "wp.use_count() = " << wp.use_count() << endl;

    cout << endl;
    bool flag = wp.expired();
    if(flag)
    {
        cout << "关联的资源已经销毁了" << endl;
    }
    else
    {
        cout << "关联的资源依旧存在" << endl;
    }
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

